# conftest.py层的代码

# coding=utf-8
import os

import allure
import pytest
from time import sleep
from selenium.webdriver import Chrome, ChromeOptions
from Common import Config
from logzero import logger

# 添加报错截图到allure报告里
driver = None


# 用例失败后自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取用例执行结果的钩子函数
    :param item:
    :param call:
    :return:
    """
    # 获取钩子方法的调度结果
    outcome = yield
    report = outcome.get_result()
    # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
    if report.when == "call" and report.failed:
        mode = "a" if os.path.exists(
            "project/demo01/TestCase/failures") else "w"
        with open("project/demo01/TestCase/failures", mode) as f:
            if "tmpir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(report.nodeid + extra + "\n")
        # 添加allure截图
        if hasattr(driver, "get_screenshot_as_png"):
            with allure.step('添加失败用例截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图",
                              allure.attachment_type.PNG)


def pytest_sessionfinish(session):
    """测试完成之前添加 environment 内容"""

    # allure报告路径
    with open(
            f"{Config.BASE_DIR}/project/{Config.period}/Report/{Config.result}/environment.properties",
            "w") as f:
        f.write("browser=chrome\nbackend=staging\ndomain=http://baidu.com")


@pytest.fixture(autouse=True, scope="session")
def d(request):
    global driver
    try:
        options = ChromeOptions()
        option_dict = {
            'argument': [
                '--disable-infobars',  # 禁止策略化
                '--start-maximized',  # 最大化运行（全屏窗口）,不设置，取元素会报错
                '--hide-scrollbars',  # 隐藏滚动条, 应对一些特殊页面
                'blink-settings=imagesEnabled=false',  # 不加载图片, 提升速度
                'user-agent="Mozilla/5.0 (Windows NT 10.0; WOW64) '
                'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"',  # 添加headers
            ],
            # 添加实验性质的参数
            'experimental': [
                {
                    'excludeSwitches': ['enable-automation', 'enable-logging']
                },
            ],
        }
        if option_dict:
            for i in option_dict.get('argument'):
                options.add_argument(i)
            for i in option_dict.get('experimental'):
                options.add_experimental_option(
                    list(i.keys())[0], sum(list(i.values()), []))
        driver = Chrome(options=options,
                        executable_path='Drivers/chromedriver.exe')
        logger.info('打开浏览器')

    except Exception as e:
        logger.error(e)
    else:

        def close_browser():
            sleep(2)
            logger.info('关闭浏览器')
            driver.quit()

        request.addfinalizer(close_browser)
        return driver
